package org.otod.security.web;

import org.otod.security.domain.User;
import org.otod.security.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	UserService userService;

	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public String userInert(@ModelAttribute("newUser") User user, Model model) {
		logger.info("用户新增");
		userService.inertUser(user);
		return userList(model);
	}

	@RequestMapping(value = "/userList", method = RequestMethod.GET)
	public String userList(Model model) {
		logger.info("用户列表");
		//		model.addAttribute("users", userService.getUserList());
		//		model.addAttribute("newUser", new User());
		return "security/userList";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String userEdit(@PathVariable Long id, Model model) {
		logger.info("用户编辑");
		model.addAttribute("user", userService.getUser(id));
		return "security/userEdit";
	}

	@RequestMapping(value = "/edited", method = RequestMethod.POST)
	public String userEdited(@ModelAttribute("user") User user, @RequestParam(value = "id", required = true) Long id,
			Model model) {
		logger.info("用户保存" + user.getId());
		userService.saveUser(user);
		return userList(model);
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String userDelete(@PathVariable Long id, Model model) {
		logger.info("用户删除" + id);
		model.addAttribute("user", userService.deleteUser(id));
		return userList(model);
	}

	@RequestMapping(value = "/userAjax", method = RequestMethod.GET)
	public String userAjax() {
		logger.info("用户ajax");
		return "security/userAjax";
	}

}
